﻿package chenji.moreitemfunapi.textures;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.Map;
import java.util.Map.Entry;

import org.bukkit.Bukkit;
import org.bukkit.scheduler.BukkitTask;

import com.google.common.collect.Maps;
import chenji.moreitemfunapi.MifAPI;
import chenji.moreitemfunapi.item.MifItem;
import chenji.moreitemfunapi.textures.info.ItemInfo;
import chenji.moreitemfunapi.textures.info.TextureInfo;
import chenji.moreitemfunapi.util.BasicTypeUtil;

public class TexturesManager {
	private final File rootpath = new File(MifAPI.getMDataFolder() + "/textures");
	private final Map<Integer, TextureInfo> textures = Maps.newHashMap();
	// Manager；
	private BukkitTask task;
	private boolean isdone;
	private Map<String, SpawnResult> results = Maps.newHashMap();

	public TexturesManager() {
		if (!rootpath.exists()) {
			rootpath.mkdirs();
		}
	}

	/**
	 * 注册含有材质的物品
	 * 
	 * @param item
	 *            物品
	 * @return
	 */
	public TextureInfo getTextureInfo(MifItem item) {
		TextureInfo info = new ItemInfo(item.getPluginName(), item.getIdentifyname(), item.getType());
		return info;
	}

	public boolean downloadItem(String url, String name) {
		try (InputStream stream = new URL(url).openConnection().getInputStream(); FileOutputStream out = new FileOutputStream(new File(rootpath + "/" + name + ".png"));) {
			byte[] data = new byte[stream.available()];
			stream.read(data);
			out.write(data);
			out.flush();
			out.close();
			return true;
		} catch (IOException e) {
			e.printStackTrace();
			return false;
		}
	}

	public boolean registerItem(MifItem item) {
		if (!item.isEnabletextures()) {
			MifAPI.getMLogger().warning("无法注册 " + item.getIdentifyname() + " 为含有材质的物品。因为其未开启材质。");
			return false;
		}
		TextureInfo info = this.getTextureInfo(item);
		info.update();
		this.textures.put(info.getUID(), info);
		return true;
	}

	public int getInfoByItemName(String name) {
		for (Entry<Integer, TextureInfo> info : this.textures.entrySet()) {
			if (info.getValue().getItemName().equalsIgnoreCase(name)) {
				return info.getKey();
			}
		}
		return -1;
	}

	public void updateTextures(int id) {
		if (this.textures.containsKey(id)) {
			this.textures.get(id).update();
		}
	}

	public void unregisterTextures(String name) {
		TextureInfo target = null;
		for (TextureInfo info : this.textures.values()) {
			if (info.getItemName().equalsIgnoreCase(name)) {
				target = info;
				break;
			}
		}
		if (target != null) {
			this.textures.remove(target);
		}
	}

	public boolean checkTexturePath(String path) {
		if (path == null) {
			return false;
		}
		File f = new File(rootpath + "/" + path);
		return f.exists();
	}

	private void runTask() {
		Bukkit.getScheduler().runTaskTimer(MifAPI.getPlugin(MifAPI.class), new Runnable() {
			@Override
			public void run() {
				task();

			}
		}, 1, 1);
	}

	private void task() {
		if (this.isdone) {
			this.task.cancel();
			this.dealResult();
		}
	}

	public void spawnPack() {
		this.isdone = false;
		this.results.clear();
		new Thread(new TexturesSpawner(this.textures.values())).start();
		;
		this.runTask();

	}

	public void setDone() {
		this.isdone = true;
	}

	public void addProblem(String name, SpawnResult i) {
		this.results.put(name, i);
	}

	public boolean contain(int uid) {
		return this.textures.containsKey(uid);
	}

	public TextureInfo getTextureInfo(int uid) {
		return this.textures.get(uid);
	}

	private void dealResult() {
		// TODO dealresult
	}

	public boolean containByIDorName(String val) {
		int id = this.getInfoByItemName(val);
		if (id != -1) {
			return this.contain(id);
		} else {
			id = BasicTypeUtil.turnToInteger(val);
			if (id != -1) {
				return this.contain(id);
			} else {
				return false;
			}
		}
	}

	public void closeTexture(String name, boolean keep) {
		int id = this.getInfoByItemName(name);
		if (id != -1) {
			if (!keep) {
				this.textures.get(id).clearAll();
			}
			this.textures.remove(id);
		} else {
			id = BasicTypeUtil.turnToInteger(name);
			if (id != -1) {
				if (!keep) {
					this.textures.get(id).clearAll();
				}
				this.textures.remove(id);
			}
		}

	}

}
